<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="title">欢迎回到 Mediotube</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="account">
          <el-input
            v-model="loginForm.account"
            placeholder="用户名或邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <div class="remember-forgot">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <router-link to="/forgot-password" class="forgot-link">忘记密码？</router-link>
        </div>
        
        <el-button type="primary" class="submit-btn" :loading="loading" @click="handleLogin">
          登录
        </el-button>
      </el-form>
      
      <div class="register-link">
        还没有账号？<router-link to="/register">立即注册</router-link>
      </div>
      
      <div class="social-login">
        <div class="divider">
          <span>或使用以下方式</span>
        </div>
        <div class="social-buttons">
          <el-button class="social-btn google" @click="handleGoogleLogin">
            <el-icon><img src="@/assets/google-icon.svg" alt="Google" /></el-icon> <!-- Corrected path -->
            Google 账号登录
          </el-button>
          <el-button class="social-btn github" @click="handleGithubLogin">
            <el-icon><img src="@/assets/github-icon.svg" alt="GitHub" /></el-icon> <!-- Corrected path -->
            GitHub 账号登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from '@/services/axios' 

const router = useRouter()
const route = useRoute()
const store = useStore()
const loading = ref(false)
const loginFormRef = ref(null)

// 登录表单
const loginForm = reactive({
  account: '',
  password: '',
  remember: false
})

// 登录表单验证规则
const loginRules = {
  account: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' },
    { min: 3, message: '用户名或邮箱至少3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
      
        const response = await axios.post('/api/auth/login', loginForm)
        const { token, user } = response.data
        // Use Vuex mutations to set token and user
        store.commit('auth/SET_TOKEN', token)
        store.commit('auth/SET_USER', user)
        ElMessage.success('登录成功')
        // 跳转到之前的页面或首页
        const redirect = route.query.redirect || '/'
        router.push(redirect)
      } catch (error) {
        let errorMessage = '登录失败，请稍后重试';
        if (error.response && error.response.data) {
          // 尝试获取后端返回的错误信息
          if (error.response.data.errors && error.response.data.errors.length > 0) {
            errorMessage = error.response.data.errors.map(err => err.msg).join(', ');
          } else if (error.response.data.error) {
            errorMessage = error.response.data.error;
          }
        }
        ElMessage.error(errorMessage);
        console.error('登录失败:', error.response || error);
      } finally {
        loading.value = false;
      }
    }
  })
}

// Google 登录处理
const handleGoogleLogin = () => {
  // 构建后端 Google 认证的 URL
  // 注意：这里的 '/api/auth/google' 是一个示例，您需要替换为实际的后端认证路由
  const googleAuthUrl = `${axios.defaults.baseURL}/api/auth/google`;
  // 跳转到 Google 认证页面
  window.location.href = googleAuthUrl;
};

// GitHub 登录处理
const handleGithubLogin = () => {
  // 构建后端 GitHub 认证的 URL
  const githubAuthUrl = `${axios.defaults.baseURL}/api/auth/github`;
  // 跳转到 GitHub 认证页面
  window.location.href = githubAuthUrl;
};

// 忘记密码
const forgotPassword = () => {
  router.push('/forgot-password')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #b4e0e7 0%, #dfe4e7 100%);
  background-size: cover;
  background-position: center;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: linear-gradient(135deg, #b4e0e7 0%, #dfe4e7 100%);
  border-radius: 8px;
  padding: 40px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  margin: auto; 
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133; /* Changed color from red */
  font-size: 24px;
  font-weight: 600;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  font-size: 14px; /* Added font-size */
}

.forgot-link {
  color: #409eff; /* Changed color */
  text-decoration: none;
}

.forgot-link:hover {
  color: #79bbff;
  text-decoration: underline;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  margin-bottom: 20px;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #606266;
  margin-bottom: 30px; /* Added margin bottom */
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  color: #79bbff;
  text-decoration: underline;
}

.social-login {
  margin-top: 30px;
}

.divider {
  display: flex;
  align-items: center;
  text-align: center;
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #e4e7ed;
}

.divider span {
  padding: 0 10px;
}

.social-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.social-btn {
  width: 100%;
  padding: 10px;
  font-size: 14px;
  justify-content: center; /* Center content */
}

.social-btn .el-icon {
  margin-right: 8px;
  font-size: 18px; /* Adjust icon size */
  display: inline-flex; /* Ensure icon aligns */
  align-items: center;
}

.social-btn img {
  width: 18px; /* Control image size */
  height: 18px;
}

.social-btn.google {
  /* Add specific styles if needed */
}

.social-btn.github {
  /* Add specific styles if needed */
}

/* Ensure prefix icons are aligned */
:deep(.el-input__prefix) {
    display: inline-flex;
    align-items: center;
}

</style>